<template>
    <ContentField>
        <div class="row justify-content-md-center">
            <div class="col-3 ">
                <form @submit.prevent="register">
                    <div>
                        <label for="username" class="form-label">用户名</label>
                        <input v-model="username" type="text" class="form-control" id="username" placeholder="请输入用户名">
                    </div>
                    <div>
                        <label for="password" class="form-label">密码</label>
                        <input v-model="password" type="password" class="form-control" id="password"
                            placeholder="请输入密码">
                    </div>

                    <div>
                        <label for="confirmedPassword" class="form-label">确认密码</label>
                        <input v-model="confirmPassword" type="password" class="form-control" id="confirmedPassword"
                            placeholder="请重新输入密码">
                    </div>
                    <div class="error_message">{{ error_message }}</div>
                    <div>
                        <button type="submit" class="btn btn-primary">注册</button>
                    </div>
                </form>
            </div>
        </div>
    </ContentField>
</template>

<script>
import ContentField from '../../../components/ContentField.vue'
import $ from 'jquery'
import { ref } from 'vue';
import router from '../../../router/index';
export default {
    components: {
        ContentField
    },
    setup() {
        let username = ref('');
        let password = ref("");
        let confirmPassword = ref("");
        let error_message = ref("");
        const register = () => {
            $.ajax({
                url: "http://127.0.0.1:3000/api/user/account/register/",
                type: "post",
                data: {
                    username: username.value,
                    password: password.value,
                    confirmPassword: confirmPassword.value,
                },
                success(resp) {
                    if (resp.error_message === "success") {
                        error_message.value = "注册成功，即将跳转登录界面";
                        setTimeout(() => {
                            router.push({ name: "user_account_login" });
                        }, 1000);
                    } else {
                        error_message.value = resp.error_message;
                    }
                }, error(resp) {
                    error_message.value = resp.error_message;
                }
            })
        }

        return {
            username,
            password,
            confirmPassword,
            error_message,
            register,
        }
    }
}
</script>

<style scoped>
button {
    width: 100%
}

div {
    margin-bottom: 10px;
}

div.error_message {
    color: red;
}
</style>